package com.gzcsqic.excelapp.utils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.util.ArrayList;
import java.util.List;

public class PrintUtil {

    /**获取当前所有打印机名*/
    public static List<String> getPrinterNames(){
        List<String> names = new ArrayList<>();
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : printServices) {
            String name = printService.getName();
            names.add(name);
        }
        return names;
    }

    public static String getDefaultPrinterName(){

        PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
        String name = printService.getName();
        return name;
    }


    public static void printFile(String filePath){
        ComThread.InitSTA();
        ActiveXComponent xl = new ActiveXComponent("Excel.Application");
        try {
            Dispatch.put(xl, "Visible", new Variant(false));
            Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
            Dispatch excel = Dispatch.call(workbooks, "Open", filePath)
                    .toDispatch();
            // 开始打印
            Dispatch.call(excel, "PrintOut");
            xl.invoke("Quit", new Variant[] {});
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 始终释放资源
            ComThread.Release();
        }
    }


    public static void printFile(String filePath,String printerName){
        ComThread.InitSTA();
        ActiveXComponent xl = new ActiveXComponent("Excel.Application");
        Dispatch excel = null;
        try {
            // 不打开文档
            Dispatch.put(xl, "Visible", new Variant(false));
            Dispatch workbooks = xl.getProperty("Workbooks").toDispatch();
            excel = Dispatch.call(workbooks, "Open", filePath)
                    .toDispatch();
            Dispatch.callN(excel,"PrintOut",new Object[]{Variant.VT_MISSING, Variant.VT_MISSING, new Integer(1),
                    new Boolean(false),printerName, new Boolean(true),Variant.VT_MISSING, ""});
            xl.invoke("Quit", new Variant[] {});
        } catch (Exception e) {
            e.printStackTrace();
            // 关闭excel进程
            if(excel != null){
                Dispatch.call(excel, "Close",new Variant(true));
            }
        } finally {

            // 始终释放资源
            ComThread.Release();

        }
    }

}
